package com.epam.iunna.bookshop.controller.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileSystemUtils {
    private static String file_separator = System.getProperty("file.separator");

    public static void copy(final File src, final String dest)
            throws IOException {
        File dest_file = new File(dest);

        copy(src, dest_file);
    }

    public static void copy(final String src, final File dest)
            throws IOException {
        File src_file = new File(src);

        copy(src_file, dest);
    }

    public static void copy(final String src, final String dest)
            throws IOException {
        File src_file = new File(src);
        File dest_file = new File(dest);

        copy(src_file, dest_file);
    }

    public static void copy(final File src, final File dest) throws IOException {
        // System.out.println("FIle System Utils copy "+src+" > "+dest);
        if (src.exists()) {
            if (src.isDirectory()) {
                if (!dest.exists()) {
                    if (!dest.mkdirs()) {
                        throw new IOException();
                    }
                }
                String[] file_list = src.list();

                for (int i = 0; i < file_list.length; i++) {
                    File src_file = new File(src + file_separator
                            + file_list[i]);
                    File dest_file = new File(dest + file_separator
                            + file_list[i]);

                    copy(src_file, dest_file);
                }
            } else {
                FileInputStream in = new FileInputStream(src);
                FileOutputStream out = new FileOutputStream(dest);
                // System.out.println("copy "+src+" > "+dest+" :" +
                // dest.exists());
                byte[] file_body = new byte[65536];
                int block_length;

                while ((block_length = in.read(file_body)) != -1) {
                    out.write(file_body, 0, block_length);
                }

                in.close();
                out.close();

                // if (!dest.setLastModified(src.lastModified())) {
                // throw new IOException();
                // }
            }
        } else {
            throw new FileNotFoundException();
        }
    }

}
